<template>
  <div class="product-manager-warp disabled-warp" style="height: calc(100vh - 104px); padding: 20px; ">
    <div class="dashboard-container"
         style=" padding: 20px 25px 10px;  ">
      <div style="line-height: 16px; flex-wrap: wrap; width: 100%; display: flex;  align-items: center;  font-size: 16px; font-family: Source Han Sans CN;font-weight: bold;color: #2F3745; ">
        <div class="dashboard-inner" style="width: 200px;">
          商品库存
          <el-tooltip class="item" effect="dark" content="温馨提示：对应列可以通过拖动改变表格宽度" placement="top">
            <i style="position: relative; left: 6px; top: 2px;" class="header-icon el-icon-info"></i>
          </el-tooltip>
        </div>
        <div style="width: calc(100% - 200px); display: flex; position: relative; top: -7px; justify-content: center;">
          <common-operation-form :list="statisticList" :marginRight="'112px'"/>
        </div>
      </div>
    </div>

    <div style="display: flex; height: calc(100% - 45px);">
      <div class="left-content" style="color: #2F3745; ">
        <tree-expansion ref="treeExpansionRef" @getCurrentNodeKey="getCurrentNodeKey" @statusChange="statusChange" />
      </div>

      <div class="right-content" style="background: #fff; " :style="`${expansionStatus? 'width: calc(100% - 260px);' : 'width: 100%;'};
            ${expansionStatus ? 'margin-left: 10px;' : 'margin-left: 0;'} `">
        <div class="product-inventory-table" :style="`margin-left: 12px; margin-right: 12px; height: 100%; width: calc(100% - 24px);`">
          <common-operation-form :list="list"/>
          <el-table style="margin-top: 15px; " fit :height="windowHeight - 30" highlight-current-row
                    @select="changeevent" ref="tableRef"  @cell-click="tableRowClick"
                    :tree-props="{children: 'children'}" row-key="id"
                    v-loading="table.loading" :data="table.data" border>
            <el-table-column :show-overflow-tooltip="true"
                label="商品名称" width="150" fixed="left" align="left">
              <template slot-scope="scope">
                <span class="table-product-hover" style="color: #1362fc;">{{ scope.row['productName'] }}</span>
              </template>
            </el-table-column>

            <template v-for="(item, index) in table.header1">
              <el-table-column :prop="item.prop" :key="index" :show-overflow-tooltip="true"
                               :width="item.width || 'auto'" :align="`center`"
                               :label="item.label">
                <template slot-scope="scope">
                  <span  v-if="item.prop === 'sellingPrice'" :style="`color: ${item.color ? item.color : ''}`">{{ isNotANumberOrEmpty(scope.row[item.prop]) ? keepTwoDecimalFull(0) : scope.row[item.prop] }}</span>
                  <span  v-else-if="item.prop === 'retailPrice'" :style="`color: ${item.color ? item.color : ''}`">{{ isNotANumberOrEmpty(scope.row[item.prop]) ? keepTwoDecimalFull(0) : scope.row[item.prop] }}</span>
                  <span  v-else-if="item.prop === 'checkStatus'" :style="`color: ${item.color ? item.color : ''}`">{{ scope.row[item.prop] ? '已盘点' : '未盘点' }}</span>
                  <span v-else-if="item.prop === 'warehouseName'">
                    <span  v-if="!scope.row.children || scope.row.children.length <= 0">
                      {{ scope.row['warehouse'] && scope.row['warehouse']['warehouseName'] }}
                    </span>
                  </span>
                  <span v-else-if="item.prop === 'purchasePrice'">
                    {{ formatAmount(scope.row[item.prop]) }}
                  </span>
                  <span v-else :style="`color: ${item.color ? item.color : ''}`">{{ scope.row[item.prop] }}</span>
                </template>
              </el-table-column>
            </template>

            <el-table-column
                label="操作" width="80" fixed="right">
              <template slot-scope="scope">
                <div style="display: flex;" v-if="!scope.row.children || scope.row.children.length <= 0">
                  <el-button size="mini" @click="detail(scope.row)" type="success">详情</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <el-pagination style="position: relative; text-align: right; margin-top: 10px;"
                         :current-page="page.pageNumber" @size-change="pageChangeEvent"
                         layout="sizes, jumper, prev, pager, next" :page-size="page.pageSize"
                         :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>

    <el-dialog style="margin-top: 10px;"
               :close-on-click-modal="false"
               width="95%" v-dialog-drag
               :title="`【${dialog.chooseItem ? dialog.chooseItem.productName : ''}】- ${dialog.chooseItem ? dialog.chooseItem.warehouseName : ''} - 库存详情`" :modal="false"
               custom-class="dialoginter7"
               :visible.sync="editDialog">
      <div>
        <common-operation-form style="margin-top: 8px;" :list="dialog.list"/>
        <el-table style="margin-top: 15px; " fit :height="windowHeight + 30" show-summary
                  @select="changeevent" ref="tableRef2" :summary-method="getSummaries2"
                  v-loading="dialog.table.loading" :data="dialog.table.data" border >
          <template v-for="(item, index) in dialog.table.header1">
            <el-table-column :prop="item.prop" :key="index" :show-overflow-tooltip="true"
                             :width="item.width || 'auto'" :align="`center`"
                             :label="item.label">
              <template slot-scope="scope">
                  <span v-if="item.prop === 'createDate'" style=" ">
                    {{ parseTime(new Date(scope.row[item.prop])) }}
                  </span>
                <span v-else-if="item.prop === 'operationType'" style=" ">
                    <el-tag effect="dark" v-if="parseFloat(scope.row['inventory']) > 0">增加</el-tag>
                    <el-tag effect="dark" v-else-if="parseFloat(scope.row['inventory']) < 0" type="success">减少</el-tag>
                    <span v-else>无变化</span>
                  </span>
                  <span v-else-if="item.prop === 'price'" style=" ">
                    {{ parseFloat(scope.row[item.prop] || 0) }}
                  </span>
                  <span v-else-if="item.prop === 'totalPrice'" style=" ">
                    {{ Math.abs(parseFloat(scope.row[item.prop] || 0)) }}
                  </span>
                  <span v-else>{{ scope.row[item.prop] }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CommonOperationForm from "@/components/CommonOperationForm/index.vue";
import CommonDialogForm from "@/components/CommonDialogForm/index.vue";
import TreeExpansion from "@/components/TreeExpansion/ProductManager.vue";
import {getInventory, getInventoryDetails, inventoryOverview} from "@/api/inventory";
import {getUserInfo} from "@/utils/auth";
import {
  documentTypeOptions,
  findRowByID,
  formatAmount,
  isNotANumberOrEmpty,
  keepTwoDecimalFull,
  parseTime
} from "../../utils";
import UnitSelect from "@/components/Unit/UnitSelect.vue";
import WarehouseSelect from "@/components/Warehouse/WarehouseSelect.vue";

export default {
  components: {WarehouseSelect, UnitSelect, CommonOperationForm, CommonDialogForm, TreeExpansion},
  data() {
    return {
      statisticList: [
        {
          type: 'statistic',
          title: '库存总数',
          value: 0,
        },
        {
          type: 'statistic',
          title: '库存总额',
          value: 0,
        },
        {
          type: 'statistic',
          title: '预估销售总额',
          value: 0,
        }
      ],
      list: [
        {
          type: 'input',
          text: '供应商姓名：',
          width: '95px',
          value: '',
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-folder-add',
          buttonText: '增加',
          event: () => {
            this.editDialog = true;
          }
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-document-add',
          buttonText: '导入',
          event: () => {

          }
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-takeaway-box',
          buttonText: '导出',
          event: () => {

          }
        },
      ],
      expansionStatus: true,
      editDialog: false,
      treeCurrentNodeKey: '',
      table: {
        data: [],
        loading: false,
        header1: [
          {
            "prop": "",
            "label": "辅助属性"
          },
          {
            "prop": "",
            "label": "规格型号"
          },
          {
            "prop": "unit",
            "label": "单位"
          },
          {
            "prop": "warehouseName",
            width: '120px',
            "label": "所属仓库"
          },
          {
            "prop": "inventory",
            "label": "当前库存",
            color: "#1362fc",
          },
          // {
          //   "prop": "warehouse",
          //   "label": "商品编号"
          // },
          {
            "prop": "purchasePrice",
            "label": "进货价(元)",
          },
          {
            "prop": "totalInventoryValue",
            "label": "库存总额(元)",
            width: '100px',
          },
          {
            "prop": "productCategoryLabel",
            "label": "商品分类"
          },
          {
            "prop": "sellingPrice",
            "label": "销售价格(元)",
            width: '100px',
          },
          {
            "prop": "retailPrice",
            "label": "零售价格(元)",
            width: '100px',
            color: "#1362fc",
          },
          {
            "prop": "shelfLocation",
            "label": "商品货位"
          },
          {
            "prop": "inventoryThreshold",
            "label": "库存阈值"
          },
          {
            "prop": "checkStatus",
            "label": "盘点状态"
          },
          {
            "prop": "remarks",
            "label": "备注"
          }
        ],
        rowSelect: -1,
      },
      dialog: {
        col: 3,
        list: [
          {
            type: 'input',
            clearable: false,
            text: '单据编号：',
            value: '',
          },
          {
            text: '制单员：',
            selectWidth: '160px',
            width: '80px',
            required: false,
            field: 'employeeSetting',
            type: 'employeeSetting',
            value: '',
          },
          {
            text: '单据类型：',
            selectWidth: '160px',
            width: '80px',
            required: false,
            field: 'documentType',
            type: 'selectAllowCreate',
            allowCreate: false,
            options: documentTypeOptions,
            value: '',
            changeEvent: (v) => {
              console.log(v);
            }
          },
          {
            type: 'button',
            buttonIcon: 'el-icon-search',
            buttonText: '搜索',
            event: () => {
              this.$message.info("此功能正在开发中, 敬请期待~");
            }
          },
        ],
        table: {
          header1: [
            {
              prop: "documentType",
              label: "单据类型",
            },
            {
              prop: "createDate",
              label: "操作时间",
              width: '180px',
            },
            {
              prop: "documentNumber",
              label: "单据编号",
              width: '150px',
            },
            {
              prop: "operationType",
              label: "操作类型",
            },
            {
              prop: "",
              label: "客户",
            },
            {
              prop: "supplierName",
              label: "供应商",
            },
            {
              prop: "inventory",
              label: "商品数量",
            },
            {
              prop: "price",
              label: "单价",
            },
            {
              prop: "totalPrice",
              label: "金额",
            },
            {
              prop: "accountName",
              label: "制单人",
            },
            {
              prop: "productRemarks",
              label: "商品备注",
            },
            {
              prop: "purchaseIncomingRemarks",
              label: "单据备注",
            }
          ],
          data: [],
          loading: false,
        },
        chooseItem: null,
        page: {
          pageSize: 10,
          pageNumber: 1,
          total: 0,
        },
      },
      page: {
        pageSize: 10,
        pageNumber: 1,
        total: 0,
      }
    }
  },
  mounted() {
    // this.requestApi();
    this.inventoryOverview();
  },
  methods: {
    formatAmount,
    parseTime,
    keepTwoDecimalFull,
    isNotANumberOrEmpty,
    inventoryOverview() {
      inventoryOverview({
        userID: getUserInfo().userID,
      }).then(res => {
        this.statisticList[0].value = res.data.data.totalInventory;
        this.statisticList[1].value = parseFloat(res.data.data.totalAmount);
        // this.statisticList[2].value = res.data.data.totalAmount;
        console.log(res);
      });
    },
    requestApi() {
      if (this.table.loading)
        return;
      this.table.loading = true;

      getInventory({
        pageSize: this.page.pageSize,
        pageNumber: this.page.pageNumber,
        userID: getUserInfo().userID,
        productCategoryID: this.treeCurrentNodeKey
      }).then(res => {
        if (res.data.code === -1) {
          this.$message.error(res.data.errMsg);
          return;
        }
        console.log(res);
        this.table.data = res.data.data;
        this.page.total = res.data.page.totalDocuments;
        this.table.loading = false;
      });
    },
    tableRowClick(row, column, cell, event) {
      let {id} = row;
      this.rowSelect = findRowByID(this.table.data, id);
      this.$refs.tableRef.setCurrentRow(this.table.data[this.rowSelect]);
      console.log(this.$refs.tableRef, this.rowSelect);
    },
    statusChange(v) {
      console.log(v);
      this.expansionStatus = v;
      this.$refs.tableRef.doLayout();
    },
    detail(item) {
      console.log("detail: ", item);
      let inventoryTable = item.inventoryTable;
      let list = [];
      for (let i = 0; i < inventoryTable.length; i++) {
        list.push(inventoryTable[i].purchaseIncomingID);
      }

      getInventoryDetails({
        inventoryTable: [...new Set(list)],
        userID: getUserInfo().userID,
      }).then(res => {
        console.log(res);
        this.dialog.chooseItem = item;
        this.dialog.table.data = res.data.data || [];
      });
      this.editDialog = true;
    },
    reloadTree() {
      this.$refs.treeExpansionRef.getProductCategory();
    },
    getCurrentNodeKey(v) {
      console.log(v);
      this.treeCurrentNodeKey = v;
      this.requestApi();
    },
    pageChangeEvent() {
      this.requestApi();
    },
    changeevent(selection, row) {
      console.log(selection, row);

    },
    getSummaries2(param) {
      const {columns, data} = param;
      const sums = [];

      columns.forEach((column, index) => {
        sums[index] = '';
      });

      this.$nextTick(() => {
        this.$refs.purchaseIncomingTableRef?.doLayout();
      });
      return sums;
    },
    setRowClass({row, rowIndex}) {
      if (row.id === this.rowSelect) {
        return 'table-current-row';
      }
      return '';
    },
    submit() {
      let data = this.$refs.commondialogformref.requiredEmpty();
      if (data) {
        this.$message.error(data.requiredMessage);
        return;
      }

      data = this.$refs.commondialogformref.getData();
      data['isDisabled'] = false;
      this.dialog.form = JSON.parse(JSON.stringify(this.dialog.copyForm));
      this.table.data.push(data);
      this.editDialog = false;
      this.$message.success("添加成功");
    }
  }
}
</script>


<style lang="scss">
.dashboard {
  &-container {
    background: #fff;
    box-shadow: 0px 0px 10px 0px rgba(45, 51, 65, 0.08);
    border-radius: 10px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.dashboard-inner {
  font-size: 16px;
  font-weight: 700;
  padding: 0 0 10px 0;
  color: #2f3745;
}



.el-scrollbar__view {
  height: 100%;
}

.el-scrollbar__wrap {
  overflow: scroll;
}

.box-card .el-card__body {
  height: 100%;
}

.left-content {
  line-height: 16px;
  flex-wrap: wrap;
  border-radius: 10px;
  display: flex;
  padding-top: 10px;
  align-items: center;
  font-size: 16px;
  font-family: Source Han Sans CN;
  font-weight: bold;
}


.right-content {
  line-height: 16px;
  flex-wrap: wrap;
  width: calc(100% - 260px);
  border-radius: 10px;
  display: flex;
  padding-top: 10px;
  margin-top: 10px;
  margin-left: 10px;
  align-items: center;
  font-size: 16px;
  font-family: Source Han Sans CN;
  font-weight: bold;
}

.table-product-hover  {
  cursor: pointer;
}

.table-product-hover:hover {
  text-underline: #3A71A8;
  text-decoration: underline;
}


</style>
